package com.maimao.user.controller.sys;

import com.maimao.api.sys.DepartmentApi;
import com.maimao.core.enums.RespCode;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.Oauth2Util;
import com.maimao.model.user.sys.Department;
import com.maimao.user.controller.base.BaseController;
import com.maimao.user.service.sys.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/12/3 7:54 下午
 */
@RestController
public class DepartmentController extends BaseController implements DepartmentApi {

    @Autowired
    private DepartmentService departmentService;

    @PreAuthorize("hasRole('sys-admin')")
    @Override
    public Result<?> getDepartmentTree() {
        return Result.okData(RespCode.OK,departmentService.departmentTree());
    }

    @Override
    public Result<?> getChild1(Integer parentId) {
        if (parentId==null){
            return Result.fail(RespCode.FAIL);
        }

        return Result.okData(RespCode.OK,departmentService.getChild1(parentId));
    }

    /**
     * 添加部门
     * @param department
     * @return
     */
    @Override
    public Result<?> addDepartment(@Valid Department department, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return Result.fail(RespCode.FAIL,bindingResult.getFieldErrors().get(0).getDefaultMessage());
        }
        boolean res = departmentService.add(department, Oauth2Util.getUserFromRequest(getRequest()));
        if(res){
            return Result.ok(RespCode.OK,"添加成功");
        }else {
            return Result.fail(RespCode.FAIL,"父部门已失效，请重新选择");
        }
    }

    @Override
    public Result<?> updateDepartment(@Valid Department department, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return Result.fail(RespCode.FAIL,bindingResult.getFieldErrors().get(0).getDefaultMessage());
        }
        if (department.getId()==null || department.getId()<1){
            return Result.fail(RespCode.FAIL,"参数错误");
        }
        boolean res = departmentService.update(department, null);
        if(res){
            return Result.ok(RespCode.OK,"修改成功");
        }else {
            return Result.fail(RespCode.FAIL,"父部门已失效，请重新选择");
        }

    }
}
